package routers

import (
	"encoding/json"
	"fmt"
	"gin/common"
	"gin/models"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

//用户登录
func UserLogin(c *gin.Context) {
	name := c.Query("name")
	if name == "" {
		common.ResponseError(c, 1001, "登录名不能为空")
		return
	}

	password := c.Query("password")
	if password == "" {
		common.ResponseError(c, 1001, "密码不能为空")
		return
	}

	userInfo := (new(models.Users)).UserInfo(name)
	fmt.Println(userInfo)
	if userInfo.Id == 0 {
		common.ResponseError(c, 1001, "用户不存在")
		return
	}

	if password != userInfo.Password {
		common.ResponseError(c, 1001, "密码错误")
		return
	}

	jsonStr, _ := json.Marshal(common.UserSession{Id: userInfo.Id, Name: userInfo.Name})

	session := sessions.Default(c)
	session.Set("user", string(jsonStr))
	session.Save()
	c.JSON(200, gin.H{"code": 0, "message": "登录成功"})
}

func UserList(c *gin.Context) {
	fmt.Println(sessions.Default(c).Get("user"))
	list := new(models.Users).UserList()
	c.JSON(200, gin.H{"code": 0, "message": "成功", "data": list})
}
